package testing;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 */

/**
 * @author xjli
 *
 */
public class XMLReader {

	/**
	 * @param args
	 */
	
	public XMLReader(){}
	
	
	public void ReadXML(String file){
		  try {   
		     File f = new File(file);
		     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
		     DocumentBuilder builder = factory.newDocumentBuilder();   
		     Document doc = builder.parse(f);   
		     NodeList nl = doc.getElementsByTagName("Diet");    
		     ReadTag(nl);  
		    } catch (Exception e) {   
		     e.printStackTrace();   
	    }   
	}
	
	public String readFile(String file){
		String content = "";
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = "";
			while ((tempString = reader.readLine()) != null) {
				content += tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		
		return content.replaceAll("\n", "");
	}
	
	public void ReadTag(NodeList nodelist){
		 for (int i = 0; i < nodelist.getLength(); i++) {   
		    Node nodes = nodelist.item(i);
		    if(nodes.hasChildNodes()){
		    	NodeList nlist = nodes.getChildNodes();
		    	ReadTag(nlist);
		    }
		    else{
		    	HandleNode(nodes);
		    }
		 }   
	}
	
	public void HandleNode(Node node){
		String value = node.getNodeValue();
		if(value == null){
			//System.out.println(node.getNodeName() + "   No Value for this node");
		}
		
		NamedNodeMap nnm = node.getAttributes();
		if(nnm != null){
			System.out.print(node.getNodeName() + "<   ");
			for(int i=0; i<nnm.getLength(); i++){
				System.out.print(nnm.item(i).getNodeName() + ": " + nnm.item(i).getNodeValue() + "  ");
			}
			System.out.println(">");
		}
		
	}
	
	//public static void main(String[] args) {
		// TODO Auto-generated method stub
	//	XMLReader xmlr = new XMLReader();
	//	xmlr.ReadXML("E:/Beef.xml");
	//}
}
